<template>
  <div class="learn-container">
    <div class="left">
      <div class="squares-container">
        <div
          v-for="i in total"
          :key="i"
          class="square_item"
          @click="index = i - 1"
          :class="{
            active: i - 1 === index,
            correct: questionStatus[i - 1] === 1,
            wrong: questionStatus[i - 1] === 2,
          }"
        >
          {{ i }}
        </div>
      </div>
    </div>
    <div class="center" ref="centerContainer">
      <div class="center_title" v-if="!reviewPage && type == '顺序练习'">
        历史正确率
        {{ selectedNum == 0 ? 0 : Math.round((rightNum / selectedNum) * 100) }}%
      </div>
      <div class="center_title" v-if="!reviewPage && type != '顺序练习'">
        当前正确率
        {{ selectedNum == 0 ? 0 : Math.round((rightNum / selectedNum) * 100) }}%
      </div>
      <div class="center_content" ref="centerContent">
        <div :key="item.id" style="margin-top: 20px; margin-bottom: 40px">
          {{ index + 1 }}.{{ item.question }}
        </div>
        <!-- 单选框组 -->
        <el-radio-group
          v-model="selectedRatio"
          v-show="item.answer.length == 1"
          class="option-group"
        >
          <div class="option-item">
            <el-radio
              :disabled="disabled"
              value="A"
              @click="radioHandler('A')"
              :label="item.item1"
            />
          </div>
          <div class="option-item">
            <el-radio
              :disabled="disabled"
              value="B"
              @click="radioHandler('B')"
              :label="item.item2"
            />
          </div>
          <div class="option-item">
            <el-radio
              :disabled="disabled"
              value="C"
              @click="radioHandler('C')"
              :label="item.item3"
            />
          </div>
          <div v-if="item.item4" class="option-item">
            <el-radio
              :disabled="disabled"
              value="D"
              @click="radioHandler('D')"
              :label="item.item4"
            />
          </div>
        </el-radio-group>

        <!-- 多选框组 -->
        <el-checkbox-group
          v-model="selectedChecked"
          v-show="item.answer.length > 1"
          class="option-group"
        >
          <div class="option-item">
            <el-checkbox value="A" :disabled="disabled">
              <div ref="check_item1">{{ item.item1 }}</div>
            </el-checkbox>
          </div>
          <div class="option-item">
            <el-checkbox value="B" :disabled="disabled">
              <div ref="check_item2">{{ item.item2 }}</div>
            </el-checkbox>
          </div>
          <div class="option-item">
            <el-checkbox value="C" :disabled="disabled">
              <div ref="check_item3">{{ item.item3 }}</div>
            </el-checkbox>
          </div>
          <div v-if="item.item4" class="option-item">
            <el-checkbox value="D" :disabled="disabled">
              <div ref="check_item4">{{ item.item4 }}</div>
            </el-checkbox>
          </div>
        </el-checkbox-group>

        <div v-if="item.item4" class="confirm_item">
          <el-button
            v-show="item.answer.length > 1"
            type="primary"
            @click="confirm"
            icon="Check"
          >
            确定
          </el-button>
        </div>
        <div>
          <div v-show="item.remark && showRemark">答案解析：</div>
          <div v-show="showRemark">{{ item.remark }}</div>
        </div>
      </div>
      <div class="func_item" ref="funcItem">
        <div class="func_item_left">
          <div class="func_item_button">
            <el-button
              type="primary"
              size="small"
              @click="showAnswer"
              icon="View"
            >
              答案
            </el-button>
          </div>
          <div class="func_item_button">
            <el-button
              :type="collectFlag ? 'success' : 'primary'"
              :icon="collectFlag ? 'Star' : 'StarFilled'"
              size="small"
              @click="collect"
            >
              收藏
            </el-button>
          </div>
        </div>
        <div class="picker_box">
          <div>
            <el-input
              v-model="nowIndex"
              min="1"
              :max="total"
              type="number"
              style="width: 60px"
              size="small"
            />
          </div>
          <div class="picker_box2">
            <el-button
              type="primary"
              size="small"
              @click="skip"
              style="margin-left: 8px"
            >
              跳转
            </el-button>
            <div class="picker_box2_2" v-if="total > 0">共{{ total }}题</div>
          </div>
        </div>
        <div class="func_item_right">
          <div class="func_item_button">
            <el-button
              type="primary"
              icon="ArrowLeft"
              size="small"
              @click="prev"
            >
              上一题
            </el-button>
          </div>
          <div class="func_item_button">
            <el-button
              type="primary"
              icon="ArrowRight"
              size="small"
              @click="next"
            >
              下一题
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, watch, onMounted } from "vue";
import { useRouter, useRoute } from "vue-router";
import { ElMessage, ElMessageBox, ElNotification } from "element-plus";
import questionItem from "@/api/questionItem/questionItem";
import collectRecord from "@/api/record/collectRecord";
import userRecord from "@/api/record/userRecord";
import selectRecord from "@/api/record/selectRecord";
import wrongRecord from "@/api/record/wrongRecord";
import selfTest from "@/api/selfTest";
import selfTestAnswer from "@/api/selfTest/selfTestAnswer";

const router = useRouter();
const route = useRoute();
const centerContainer = ref(null);
const centerContent = ref(null);
const reviewPage = ref(false);
const recordedAns = ref([]);
const showRemark = ref(false);
let type = null;
let selectedId = null;
const index = ref(0);
const total = ref(0);
const items = ref([]);
const item = ref({
  subject: "",
  question: "",
  item1: "",
  item2: "",
  item3: "",
  item4: "",
  answer: "",
  remark: "",
});
const selectedRatio = ref("");
const selectedChecked = ref([]);
const collectFlag = ref(false);
const rightNum = ref(0);
const selectedNum = ref(0);
const nowIndex = ref(1);
const disabled = ref(false);

// 添加一个数组来跟踪题目状态：0-未答题，1-答对，2-答错
const questionStatus = ref([]);

watch(index, (newVal, oldVal) => {
  nowIndex.value = newVal + 1;
  selectedRatio.value = "";
  selectedChecked.value = [];
  item.value = items.value[newVal];
  reviewSelected(newVal);
  checkCollect();
  showRemark.value = false;
  sentToServer(newVal, oldVal);
});

const skip = () => {
  if (nowIndex.value < 1) {
    ElNotification({ type: "danger", message: "跳转页码不合法！" });
    return;
  }
  if (nowIndex.value > total.value) {
    ElNotification({ type: "danger", message: "跳转页码不合法！" });
    return;
  }
  index.value = parseInt(nowIndex.value) - 1;
};

const sentToServer = async (newVal, oldVal) => {
  if (type == "顺序练习") {
    userRecord.updateOrAdd(
      index.value,
      selectedId,
      rightNum.value,
      selectedNum.value
    );
    const jsonStr = JSON.stringify(recordedAns.value);

    selectRecord.updateOrAdd(jsonStr, selectedId, questionStatus.value);
  }
};

const reviewSelected = (newVal) => {
  let res = recordedAns.value[newVal].filter((a) => a != "");
  if (res.length > 1) {
    selectedChecked.value = res;
  }
  if (res.length == 1) {
    selectedRatio.value = res[0];
  }
};

const checkCollect = async () => {
  const res = await collectRecord.checkCollect(item.value.id);
  if (res.data == "收藏过") {
    collectFlag.value = true;
  } else {
    collectFlag.value = false;
  }
};

const showAnswer = () => {
  if (item.value.answer.length == 1) {
    selectedRatio.value = item.value.answer;
  } else {
    let arr = item.value.answer.split("+");
    selectedChecked.value = arr;
  }
};

const collect = () => {
  collectFlag.value = !collectFlag.value;
  let flag = collectFlag.value ? 1 : 0;
  collectRecord.updateCollect(item.value.id, flag, route.query.selectedId);
};

const next = () => {
  if (index.value == total.value - 1) {
    ElMessage({
      message: "已经是最后一题了！",
      type: "error",
    });
    return;
  }
  index.value = index.value + 1;
};

const prev = () => {
  if (index.value == 0) {
    ElMessage({
      message: "已经是第一题了！",
      type: "error",
    });
    return;
  }
  index.value = index.value - 1;
};

const checkIfNotAnswered = () => {
  const arr = recordedAns.value[index.value].filter((item) => item != "");
  let flag = false;
  if (arr.length > 0) {
    //表示以前做过这道题
    flag = false;
  } else {
    flag = true;
  }
  return flag;
};

const radioHandler = (selected) => {
  if (!selected) {
    ElNotification({ type: "warning", message: "请选择您的选项!" });
    return;
  }

  const flag = checkIfNotAnswered();

  if (selected === item.value.answer) {
    ElNotification({
      type: "success",
      message: "回答正确!",
      duration: 1500,
    });

    if (flag) {
      rightNum.value++;
      selectedNum.value++;
      if (type == "错题练习") {
        wrongRecord.deleteByQuestionId(item.value.id);
      }
    }
    showRemark.value = true;
    questionStatus.value[index.value] = 1; // 标记为答对

    // 记录答案
    recordedAns.value[index.value] = [selected];

    // 如果不是最后一题，自动进入下一题
    if (index.value < total.value - 1) {
      disabled.value = true;
      disabled.value = true;
      setTimeout(() => {
        next();
        disabled.value = false;
      }, 1500);
    }
  } else {
    ElNotification({
      type: "error",
      message: "回答错误!",
      duration: 1500,
    });
    if (flag) {
      if (type != "错题练习") {
        wrongRecord.addWrongRecord(item.value.id, selectedId);
      }
      selectedNum.value++;
    }
    questionStatus.value[index.value] = 2; // 标记为答错

    // 记录错误答案
    recordedAns.value[index.value] = [selected];

    // 如果是错题练习，不自动进入下一题
    if (type !== "错题练习") {
      disabled.value = true;
      setTimeout(() => {
        next();
        disabled.value = false;
      }, 1500);
    }
  }
};

const confirm = () => {
  if (!selectedChecked.value || selectedChecked.value.length === 0) {
    ElNotification({ type: "warning", message: "请选择您的选项!" });
    return;
  }

  const sortedAnswer = item.value.answer.split("+").sort().join("+");
  const sortedSelected = selectedChecked.value.sort().join("+");

  const flag = checkIfNotAnswered();

  if (sortedSelected === sortedAnswer) {
    ElNotification({
      type: "success",
      message: "回答正确!",
      duration: 1500,
    });
    if (flag) {
      rightNum.value++;
      selectedNum.value++;
      if (type == "错题练习") {
        wrongRecord.deleteByQuestionId(item.value.id);
      }
    }
    showRemark.value = true;
    questionStatus.value[index.value] = 1; // 标记为答对

    // 记录答案
    recordedAns.value[index.value] = selectedChecked.value;

    // 如果不是最后一题，自动进入下一题
    if (index.value < total.value - 1) {
      disabled.value = true;
      setTimeout(() => {
        next();
        disabled.value = false;
      }, 1500);
    }
  } else {
    ElNotification({
      type: "error",
      message: "回答错误!",
      duration: 1500,
    });
    if (flag) {
      if (type != "错题练习") {
        wrongRecord.addWrongRecord(item.value.id, selectedId);
      }
      selectedNum.value++;
    }
    questionStatus.value[index.value] = 2; // 标记为答错

    // 记录错误答案
    recordedAns.value[index.value] = selectedChecked.value;

    // 如果是错题练习，不自动进入下一题
    if (type !== "错题练习") {
      disabled.value = true;
      setTimeout(() => {
        next();
        disabled.value = false;
      }, 1500);
    }
  }
};

const returnToIndex = (notify) => {
  ElNotification({
    type: "danger",
    message: notify,
  });
  router.push({
    path: "/learning/index",
  });
};

const initItems = (res) => {
  items.value = res.data;
  item.value = items.value[0];
  total.value = items.value.length;
  questionStatus.value = Array(total.value).fill(0); // 重置状态数组
};

const initRecordsAns = () => {
  for (let index = 0; index < total.value; index++) {
    recordedAns.value.push(new Array());
  }
};

const getQuestions = async () => {
  // 如果没有必要的路由参数，直接返回首页
  if (
    !route.query.type ||
    (!route.query.question &&
      !route.query.selfTestId &&
      !route.query.selectedId)
  ) {
    router.push({
      path: `/learning/index`,
    });
    return;
  }

  try {
    if (route.query.type == "随机练习" && route.query.question != undefined) {
      type = route.query.type;
      const res = await questionItem.getLearnItemsByQuestion(
        route.query.question
      );
      if (res.data.length == 0) {
        returnToIndex("搜索无结果！");
        return;
      }
      initItems(res);
      initRecordsAns();
      await checkCollect();
    } else if (
      route.query.selfTestId != undefined &&
      route.query.type == "回顾错题"
    ) {
      type = "随机练习";
      reviewPage.value = true;
      const res = await selfTest.geBySelfTestId(route.query.selfTestId);

      initItems(res);
      initSelfRecord();
      await checkCollect();
    } else if (
      route.query.selectedId != undefined &&
      route.query.type != undefined
    ) {
      selectedId = route.query.selectedId;
      type = route.query.type;

      const res = await questionItem.getLearnItems(
        route.query.type,
        route.query.selectedId
      );

      if (res.data.length == 0) {
        if (type == "错题练习") {
          returnToIndex("您没有错题！请继续保持！");
          router.push({
            path: "/learning/index",
          });
          return;
        }
        if (type == "收藏练习") {
          returnToIndex("您没有收藏任何题目！");
          router.push({
            path: "/learning/index",
          });
          return;
        }
      }
      initItems(res);
      await checkCollect();
      if (type == "顺序练习") {
        getRecord();
      } else {
        initRecordsAns();
      }
    }
  } catch (error) {
    console.error("Error in getQuestions:", error);
    // returnToIndex("加载题目时发生错误");
  }
};

const reset = (res) => {
  ElMessageBox.confirm("重新来过会清空您该章节的所有记录，是否确认？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
    cancelButtonColor: "green",
  })
    .then(() => {
      userRecord.deleteBySelectId(selectedId).then((response) => {
        ElNotification({ type: "success", message: `${response.data}` });
        for (let index = 0; index < total.value; index++) {
          recordedAns.value.push(new Array());
        }
      });
      questionStatus.value = Array(total.value).fill(0);
    })
    .catch(() => {
      rightNum.value = res.data.rightNum;
      selectedNum.value = res.data.selectedNum;
      initRecords(res.data.indexRecord);
    });
};

const resetConfirm = (res) => {
  ElMessageBox.confirm(
    `您上一次练习到第${res.data.indexRecord + 1}题，是否继续？`,
    "提示",
    {
      confirmButtonText: "继续练习",
      cancelButtonText: "重新来过",
      type: "info",
      cancelButtonColor: "red",
      confirmButtonColor: "green",
    }
  )
    .then(() => {
      rightNum.value = res.data.rightNum;
      selectedNum.value = res.data.selectedNum;
      initRecords(res.data.indexRecord);
    })
    .catch(() => {
      reset(res);
    });
};

const initSelfRecord = () => {
  selfTestAnswer.geBySelfTestId(route.query.selfTestId).then((res) => {
    recordedAns.value = res.data;
    for (let index = 0; index < recordedAns.value.length; index++) {
      const element = recordedAns.value[index];
      const arr = element.filter((item) => item != "");
      if (arr.length == 0) {
        questionStatus.value[index] = 0;
      } else if (arr.length == 1) {
        const ans = arr[0];
        if (ans == items.value[index].answer) {
          questionStatus.value[index] = 1;
        } else {
          questionStatus.value[index] = 2;
        }
      } else {
        const arrToStr = arr.sort().join("+");
        if (arrToStr == items.value[index].answer) {
          questionStatus.value[index] = 1;
        } else {
          questionStatus.value[index] = 2;
        }
      }
    }
    reviewSelected(0);
  });
};

const getRecord = () => {
  userRecord.getBySelectId(selectedId).then((res) => {
    if (res.data) {
      resetConfirm(res);
    } else {
      for (let index = 0; index < total.value; index++) {
        recordedAns.value.push(new Array());
      }
    }
  });
};

const initRecords = (param) => {
  selectRecord.getBySelectId(selectedId).then((res) => {
    if (!res.data) {
      for (let index = 0; index < total.value; index++) {
        recordedAns.value.push(new Array());
      }
    } else {
      if (res.data.length != total.value) {
        let arr = JSON.parse(res.data.result.selected);

        for (let index = 0; index < total.value - res.data.length; index++) {
          let emptyArr = [];
          for (let i = 0; i < 4; i++) {
            emptyArr.push("");
          }
          arr.push(emptyArr);
        }
        recordedAns.value = arr;
      } else {
        if (res.data.result.selected) {
          recordedAns.value = JSON.parse(res.data.result.selected);
        }
        if (res.data.result.questionStatus) {
          questionStatus.value = JSON.parse(res.data.result.questionStatus);
        }
      }
    }
    index.value = param;
  });
};

onMounted(async () => {
  //设置center_content的高度是centerContainer.value.clientHeight - 10 - 50 - 70
  centerContent.value.style.height =
    centerContainer.value.clientHeight - 10 - 50 - 70 + "px";
  await getQuestions();
});
</script>

<style scoped>
.learn-container {
  display: flex;
  margin-top: 10px;
}

.left {
  width: 300px;
  padding: 10px;
  background-color: white;
  height: 70vh;
  overflow-y: auto;
  overflow-x: hidden;
  border: 1px solid rgb(226, 226, 226);
  border-radius: 3px;
}

.left::-webkit-scrollbar {
  width: 6px;
}

.left::-webkit-scrollbar-thumb {
  background-color: #dcdfe6;
  border-radius: 3px;
}

.left::-webkit-scrollbar-track {
  background-color: #f5f5f5;
}

.center {
  margin-left: 1%;
  width: 84%;
  padding: 10px;
  height: 70vh;
  border: 1px solid rgb(226, 226, 226);
  border-radius: 3px;
  background-color: white;
}

.center_title {
  height: 50px;
  border-radius: 2px;
  padding-left: 10px;
}

.center_content {
  overflow-y: auto;
}

.func_item {
  height: 50px;
  margin-top: 20px;
  bottom: 0;
  left: 0;
  width: 100%;
  display: flex;
  justify-content: center;
}

.squares-container {
  display: grid;
  grid-template-columns: repeat(5, 1fr);
  gap: 10px;
  padding: 10px;
}

.square_item {
  background-color: rgb(245, 245, 245);
  border: 1px solid rgb(232, 221, 221);
  border-radius: 2px;
  width: 35px;
  height: 25px;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
}

.square_item.correct {
  background-color: #67c23a !important;
  color: white;
  border-color: #67c23a;
}

.square_item.wrong {
  background-color: #f56c6c !important;
  color: white;
  border-color: #f56c6c;
}

/* 确保当前选中的题目样式优先级更高 */
.square_item.active {
  background-color: #409eff !important;
  color: white;
  border-color: #409eff;
}

.confirm_item {
  margin-top: 40px;
  height: 65px;
}

.picker_box {
  display: flex;
  justify-content: left;
  height: 32px;
  border-radius: 2px;
  width: 30%;
  margin-right: 2px;
  margin-left: 2px;
  text-align: center;
  font-size: 20px;
}

.picker_box2 {
  width: 78px;
}
.picker_box2_1 {
  font-size: 14px;
  color: white;
  margin-left: 2px;
  background-color: #5599ff;
  border-radius: 2px;
}
.picker_box2_2 {
  font-size: 12px;
  margin-left: 2px;
}
.func_item_left {
  width: 29%;
  display: flex;
  justify-content: left;
}
.func_item_right {
  width: 39%;
  display: flex;
  justify-content: right;
}
.func_item_button {
  margin: 0 4px;
}

/* 修改一些样式以适应 Element Plus */
.el-radio-group,
.el-checkbox-group {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.el-radio,
.el-checkbox {
  margin-right: 0;
}

.picker_box2_1 {
  display: inline-block;
  margin-left: 8px;
}

/* 添加新的样式 */
.option-group {
  width: 100%;
  padding: 0 20px;
}

.option-item {
  width: 100%;
  margin-top: 10px;
}

.option-item :deep(.el-radio),
.option-item :deep(.el-checkbox) {
  width: 100%;
  margin-right: 0;
  padding: 8px 0;
}

.option-item :deep(.el-radio__label),
.option-item :deep(.el-checkbox__label) {
  white-space: normal;
  word-break: break-word;
}
</style>
